<?php

namespace app\api\Logic\Course;

use app\api\Logic\Campusclass\CampusClassLogic;
use app\api\Logic\Campusclass\CampusClassStudentLogic;
use app\api\model\CampusCourseOrderModel;
use app\api\model\CampusCourseOrderSublevelModel;
use app\api\model\PayLogModel;
use app\api\model\UserModel;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class ManagementOrderLogic
{
    /**
     * 支付成功，用于支付成功回调用
     * @param $params
     * @return bool
     */
    public function payment($params)
    {
        Db::startTrans();
        try {
            // 加锁获取订单信息
            $orderInfo = CampusCourseOrderModel::where('no', $params['out_trade_no'])
                ->field('id,shop_id,user_id,status')
                ->lock(true)
                ->find();
            $orderInfo = objToArray($orderInfo) ?? [];
            if (empty($orderInfo) || $orderInfo['status'] != 1) {
                return false;
            }

            //加锁获取订单子项信息
            $orderSublevelInfo = CampusCourseOrderSublevelModel::where('no', $params['out_trade_no'])
                ->field('id,gs_id,m_type,m_type_num,all_num,status,type,type')
                ->lock(true)
                ->find();
            $orderSublevelInfo = objToArray($orderSublevelInfo) ?? [];
            if (empty($orderSublevelInfo) || $orderSublevelInfo['status'] != 0) {
                return false;
            }

            // 修改支付单信息
            $updateInfo = [
                'status' => 2,
                'pay_time' => time()
            ];
            CampusCourseOrderModel::where('no', $params['out_trade_no'])->update($updateInfo);


            //订单子项为天或者月单位，则end_time有值
            $startTime = time();
            $endTime = 0;
            if ($orderSublevelInfo['m_type'] == 'monthly') {
                //todo 这边一个月默认30天，若需严格按照日历天数，则另写接口计算
                $endTime = $startTime + $orderSublevelInfo['all_num'] * 30 * 3600 * 24;
            } else if ($orderSublevelInfo['m_type'] == 'day') {
                $endTime = $startTime + $orderSublevelInfo['all_num'] * 24 * 3600;
            }

            // 修改订单子项信息
            $updateSublevelData = [
                'status' => 1,
                'start_time' => $startTime,
                'end_time' => $endTime
            ];
            CampusCourseOrderSublevelModel::where('no', $params['out_trade_no'])->update($updateSublevelData);

            //获取课程详情
            $managementLogic = new ManagementLogic();
            $courseInfo = $managementLogic->managementInfo($orderSublevelInfo['gs_id']);
            //如果课程是一对一，则生成对应记录
            if($courseInfo['class_type'] == 2){
                $campusClassLogic = new CampusClassLogic();
                $campusClassStudentLogic = new CampusClassStudentLogic();
                //获取用户信息
                $userInfo = UserModel::where('id',$orderInfo['user_id'])
                    ->field('id,truename')
                    ->find();
                $userInfo = objToArray($userInfo) ?? [];
                $userName = $userInfo['truename'] ?? '';
                //生成一个新的班级
                $classId = $campusClassLogic->createOneOnOneClass([
                    'shop_id' => $orderInfo['shop_id'],
                    'name' => $courseInfo['name'].'_'.$userName,
                    'course_id' => $courseInfo['id']
                ]);

                //生成班级学员记录
                $campusClassStudentLogic->insert([
                    'shop_id' => $orderInfo['shop_id'],
                    'class_id' => $classId,
                    'user_id' => $userInfo['id'],
                    'course_id' => $courseInfo['id'],
                    'all_class_hour' => $orderSublevelInfo['all_num']
                ]);
            }

            //查询主订单ID
            $payLogInfo = PayLogModel::where('controller','course/management_order')
                ->where('order_id',$orderInfo['id'])
                ->where('shop_id',$orderInfo['shop_id'])
                ->field('id,coupon_id')
                ->find();
            $payLogInfo = objToArray($payLogInfo) ?? [];
            if(!empty($payLogInfo)){
                //todo 执行优惠券核销动作，优惠券状态改成已使用等，待接口，后面补上

                //todo 额外数据，用于保存交易单号等信息，由于不知道回调返回的参数，因此这边暂时为空
                $expandData = [
                    'transaction_id' => ''
                ];
                //执行主订单回调
                $this->payLogNotify($payLogInfo['id'],$expandData);
            }

            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 主订单回调
     * @param $orderId
     * @param null $expandData
     * @return false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payLogNotify($orderId, $expandData = null)
    {
        // 加锁获取订单信息
        $orderInfo = PayLogModel::where('id', $orderId)
            ->lock(true)
            ->find();
        $orderInfo = objToArray($orderInfo) ?? [];
        if (empty($orderInfo)) {
            return false;
        }
        if ($orderInfo['status'] != 0) {
            return false;
        }

        // 修改支付单信息
        $updateInfo = [
            'status' => 1,
            'pay_time' => time()
        ];
        $updateInfo = array_merge($expandData, $updateInfo);

        PayLogModel::where('id', $orderId)->update($updateInfo);

        return true;
    }

    /**
     * 专项课列表
     * @param $params
     * @param bool $isLimit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderList($params,$isLimit = false){
        $query = CampusCourseOrderModel::where('shop_id',$params['shop_id'])
            ->where('user_id',$params['user_id'])
            ->where('style',1)
            ->where('status',2)
            ->with([
                'mallGoodsInfo' => function ($query) {
                    $query->withField('id,name,price,cost_price,image');
                },
                'managementOrderInfo' => function ($query) {
                    $query->withField('no,type,gs_id,m_type,m_type_num,status,all_num,use_num,start_time,end_time');
                }
            ])->field('id,no,style,price,name,image,status,goods_id')
            ->order('createtime','desc');

        //分页
        if($isLimit){
            $list = $query->paginate(PAGE_SIZE);
            $res = objToArray($list) ?? [];
        }else{
            $list = $query->select();
            $res['data'] = objToArray($list) ?? [];
        }

        return $res;
    }
}
